<?php
/**
 * Created by PhpStorm.
 * User: mayn
 * Date: 2018/9/20
 * Time: 16:13
 */

namespace app\api\models;

use cm;
use Yii;
use app\api\core\wechat\wxAction;
use app\api\core\wechat\wxUser;
use yii\base\Model;

class MainModel extends Model
{
    public function actionArticleDetails()
    {
        $tpl = 'article';
        $id = $this->get('id', $this->get('state'));
        if (!empty($id)) {
            $article = Cm::$db->one("SELECT 
            u.accountappid,u.accountverifytype,a.* FROM `scrm_weixin_article` as a 
            INNER JOIN `scrm_weixin_account` as u ON u.id=a.wx_account_id
            WHERE a.id='{$id}'");

            $openid = '';
            if (!empty($article)) {
                $code = $this->get('code');
                $wechat = new wxAction($article['accountappid']);
                if (!empty($code)) {
                    $callback = 'http://' . $_SERVER['SERVER_NAME'] . ($_SERVER["SERVER_PORT"] == 80 ? '' : ':' . $_SERVER["SERVER_PORT"]) . $_SERVER["REQUEST_URI"];

                    $oauth2Url = $wechat->getOauthRedirectTreeOpenPlatform($callback, $id, 'snsapi_base');
                    header("Content-type: text/html; charset=utf-8");
                    header("Cache-Control: no-cache");
                    header("Pragma: no-cache");
                    header("Location:" . $oauth2Url);
                } else {
                    $result = $wechat->getOauthAccessTokenTreeOpenPlatform();
                    if (!empty($result) && isset($result['openid'])) {
                        //获取用户
                        (new wxUser())->getUserInfo($result['openid']);
                        $openid = $result['openid'];

                    }
                }
            }
        } else {
            $article = [];
            $tpl = 'page';#空白页面
        }

        return [
            'list'=>$article,
            'tpl'=>$tpl,
        ];
    }

    public function get($key=null, $default='')
    {
        return $key ? \Yii::$app->request->get($key, $default) : \Yii::$app->request->get();
    }
    public function post($key=null, $default='')
    {
        return $key ? \Yii::$app->request->post($key, $default) : \Yii::$app->request->post();
    }
}